package com.scholarship.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scholarship.system.common.dto.Result;
import com.scholarship.system.entity.PoliticalPerformance;
import com.scholarship.system.entity.Student;
import com.scholarship.system.mapper.PoliticalMapper;
import com.scholarship.system.mapper.StudentMapper;
import com.scholarship.system.service.PoliticalService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Year;
import java.time.MonthDay;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 思政表现评分服务实现类
 */
@Service
public class PoliticalServiceImpl extends ServiceImpl<PoliticalMapper, PoliticalPerformance>
        implements PoliticalService {

    private static final Logger logger = LoggerFactory.getLogger(PoliticalServiceImpl.class);

    @Autowired
    private PoliticalMapper politicalMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Result<List<Map<String, Object>>> getPoliticalScoreList(Long advisorId, String keyword, Integer year,
            String semester) {
        try {
            // 设置默认值
            if (year == null) {
                year = Year.now().getValue();
            }
            if (semester == null) {
                int month = MonthDay.now().getMonthValue();
                semester = month >= 2 && month <= 7 ? "春季" : "秋季";
            }

            // 使用Mapper查询
            List<Map<String, Object>> result = politicalMapper.selectPoliticalScoreList(advisorId, keyword, year,
                    semester);
            return Result.success(result);
        } catch (Exception e) {
            logger.error("获取思政评分列表异常", e);
            return Result.error("获取思政评分列表失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Map<String, Object>> getPoliticalScoreDetail(Long studentId, Integer year, String semester) {
        try {
            // 查询学生基本信息
            String studentSql = "SELECT s.id, s.student_id, u.name, s.college, s.major, s.grade, s.class_name " +
                    "FROM student s LEFT JOIN user u ON s.user_id = u.id WHERE s.id = ?";
            Map<String, Object> studentInfo = jdbcTemplate.queryForMap(studentSql, studentId);

            // 查询思政评分信息
            LambdaQueryWrapper<PoliticalPerformance> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PoliticalPerformance::getStudentId, studentId)
                    .eq(PoliticalPerformance::getYear, year)
                    .eq(PoliticalPerformance::getSemester, semester);
            PoliticalPerformance politicalPerformance = getOne(wrapper);

            Map<String, Object> politicalInfo = new HashMap<>();
            if (politicalPerformance != null) {
                politicalInfo.put("id", politicalPerformance.getId());
                politicalInfo.put("student_id", politicalPerformance.getStudentId());
                politicalInfo.put("base_score", politicalPerformance.getBaseScore());
                politicalInfo.put("honor_score", politicalPerformance.getHonorScore());
                politicalInfo.put("advisor_score", politicalPerformance.getAdvisorScore());
                politicalInfo.put("advisor_comment", politicalPerformance.getAdvisorComment());
                politicalInfo.put("total_score", politicalPerformance.getTotalScore());
                politicalInfo.put("year", politicalPerformance.getYear());
                politicalInfo.put("semester", politicalPerformance.getSemester());
            } else {
                // 如果没有记录，创建默认值
                politicalInfo.put("id", null);
                politicalInfo.put("student_id", studentId);
                politicalInfo.put("base_score", 0);
                politicalInfo.put("honor_score", 0);
                politicalInfo.put("advisor_score", null);
                politicalInfo.put("advisor_comment", null);
                politicalInfo.put("total_score", 0);
                politicalInfo.put("year", year);
                politicalInfo.put("semester", semester);
            }

            // 查询荣誉记录
            String honorSql = "SELECT * FROM honor_record WHERE student_id = ? AND year = ? AND semester = ? ORDER BY award_date DESC";
            List<Map<String, Object>> honorList = jdbcTemplate.queryForList(honorSql, studentId, year, semester);

            // 组装结果
            Map<String, Object> result = new HashMap<>();
            result.put("studentInfo", studentInfo);
            result.put("politicalInfo", politicalInfo);
            result.put("honorList", honorList);

            return Result.success(result);
        } catch (Exception e) {
            logger.error("获取思政评分详情异常", e);
            return Result.error("获取思政评分详情失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> savePoliticalScore(Map<String, Object> params) {
        try {
            logger.info("保存思政评分，参数: {}", params);

            // 参数校验
            if (params.get("studentId") == null) {
                return Result.error("学生ID不能为空");
            }
            if (params.get("year") == null) {
                return Result.error("评分年份不能为空");
            }
            if (params.get("semester") == null) {
                return Result.error("评分学期不能为空");
            }

            Long studentId;
            try {
                studentId = Long.parseLong(params.get("studentId").toString());
            } catch (NumberFormatException e) {
                logger.error("学生ID格式错误: {}", params.get("studentId"));
                return Result.error("学生ID格式错误");
            }

            Integer year;
            try {
                year = Integer.parseInt(params.get("year").toString());
            } catch (NumberFormatException e) {
                logger.error("年份格式错误: {}", params.get("year"));
                return Result.error("年份格式错误");
            }

            String semester = params.get("semester").toString();

            // 查询是否存在记录
            LambdaQueryWrapper<PoliticalPerformance> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PoliticalPerformance::getStudentId, studentId)
                    .eq(PoliticalPerformance::getYear, year)
                    .eq(PoliticalPerformance::getSemester, semester);
            PoliticalPerformance politicalPerformance = getOne(wrapper);

            if (politicalPerformance == null) {
                // 创建新记录
                politicalPerformance = new PoliticalPerformance();
                politicalPerformance.setStudentId(studentId);
                politicalPerformance.setYear(year);
                politicalPerformance.setSemester(semester);
            }

            // 设置评分信息，处理可能的空值或格式错误
            try {
                politicalPerformance.setBaseScore(params.get("baseScore") == null ? BigDecimal.ZERO
                        : new BigDecimal(params.get("baseScore").toString()));

                politicalPerformance.setHonorScore(params.get("honorScore") == null ? BigDecimal.ZERO
                        : new BigDecimal(params.get("honorScore").toString()));

                if (params.get("advisorScore") != null && !params.get("advisorScore").toString().isEmpty()) {
                    politicalPerformance.setAdvisorScore(new BigDecimal(params.get("advisorScore").toString()));
                }
            } catch (NumberFormatException e) {
                logger.error("分数格式错误: {}", e.getMessage());
                return Result.error("分数格式错误: " + e.getMessage());
            }

            politicalPerformance.setAdvisorComment((String) params.get("advisorComment"));

            // 不要手动设置总分，让数据库的生成列计算
            // 数据库中total_score是生成列: GENERATED ALWAYS AS (base_score + honor_score +
            // IFNULL(advisor_score, 0)) STORED

            logger.info("保存思政评分，实体: {}", politicalPerformance);

            // 保存或更新
            boolean success = saveOrUpdate(politicalPerformance);

            if (success) {
                logger.info("思政评分保存成功，ID: {}", politicalPerformance.getId());
                return Result.success();
            } else {
                logger.error("思政评分保存失败");
                return Result.error("保存失败，请稍后重试");
            }
        } catch (Exception e) {
            logger.error("保存思政评分异常", e);
            return Result.error("保存思政评分失败: " + e.getMessage());
        }
    }
}